package springboot.intercepter;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import springboot.common_utils.JWTUtils;
import springboot.common_utils.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 * @author daiqiang
 * @since 2024/5/24-16:01
 */
@Slf4j
@Component
public class JwtValidateInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("X-Token");
        log.debug(request.getRequestURI() + "需要验证：" + token);
        if (token != null) {
            try {
                JWTUtils.parseToken(token);
                log.debug(request.getRequestURI() + "验证通过");
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        log.debug(request.getRequestURI() + "验证失败，禁止访问");
        response.setContentType("application/json;charset=utf-8");
        R<Object>  fail= R.fail(20003,"jwt无效，请重新登录!");
        response.getWriter().write(JSON.toJSONString(fail));
        return false;//拦截
    }

}
